
package gui.polish;

import java.lang.reflect.Array;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import utilities.Services;

import javax.swing.BoxLayout;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JSeparator;

import java.awt.Label;

import javax.swing.JLabel;
import javax.swing.SwingConstants;

import java.awt.TextArea;

import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.RowSorter;

import entities.PolishFrameEntity;
import gui.VPOfOperations.VPOfOperationsMain;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.JTabbedPane;
import javax.swing.border.TitledBorder;

import java.awt.Font;

import javax.swing.ListSelectionModel;

import com.jgoodies.common.base.Objects;

import clients.RPCClient;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLayeredPane;
import javax.swing.JToolBar;
import javax.swing.JTextField;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

import net.miginfocom.swing.MigLayout;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import java.awt.BorderLayout;

import javax.swing.UIManager;

import java.awt.Color;

import javax.swing.border.EtchedBorder;
/**
 * This panel is the polish department GUI first menu , it includes a tracking of all the rolling jars at that point of time , it initializes the polishIDserarchPanel if
 * it is clicked by user , also it initializes the startNewPolishPanel if needed to create a new polish polish .
 */
public class PolishPanel extends JPanel {
	private PolishFrame myFrame;
	private PolishPanel myPolishPanel; 
	private StartPolishPanel myStartPolish;
	private JTable table;
	private Object selectedObject;
	private OrderIDSearchPanel myOrderIDSerchPanel ;
	private int selectedRowIndex = -1;
	private int selectedColumnIndex = -1;
	private RPCClient polishClient ;
	private MyInfoFrame myInfoFrame;
	private ArrayList<String> pelletsArray;
	public static Boolean youCanUpdatePelletsDB;
/**
 * Constructor	
 * @param polishFrame 
 */
	public PolishPanel(PolishFrame polishFrame) {
		setBackground(new Color(173, 216, 230));
		setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "\u05D1\u05E7\u05E8\u05EA \u05DC\u05D9\u05D8\u05D5\u05E9", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));
		myFrame = polishFrame;
		myPolishPanel=this;
		setLayout(new MigLayout("", "[grow][173px][67px][112px][3px][12px][31px][28px][39px][142px][grow]", "[grow][22px][23px][22px][3px][grow][24px][23px][][grow]"));
		
		JButton button = new JButton("חיפוש לפי פק\"ע");
		button.setFont(new Font("Tahoma", Font.PLAIN, 13));
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				myOrderIDSerchPanel = new OrderIDSearchPanel(myFrame , myPolishPanel);
				myFrame.setContentPane(myOrderIDSerchPanel);
				myFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
				myFrame.setVisible(true);
			}
		});
		button.setIcon(new ImageIcon(PolishPanel.class.getResource("/graphics/searchOrder.png")));
		add(button, "cell 9 2,alignx left,growy");
		
		JButton button_1 = new JButton("רענן");
		button_1.setFont(new Font("Tahoma", Font.PLAIN, 13));
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ArrayList<Object> message = new ArrayList<>();
				ArrayList<Object> respond=null;
				message.add("initializePolishPane");
				try{
					polishClient = new RPCClient();
					respond = polishClient.call(message);
					if(respond.get(1).equals("valid"))
						setVariables(respond);
					else{
						
					} 
				}
				catch (Exception e1)
				{
					System.out.println(e1);
				}
				selectedColumnIndex=-1;
				selectedRowIndex=-1;
			}
		});
		button_1.setIcon(new ImageIcon(PolishPanel.class.getResource("/graphics/refreshOrders.png")));
		add(button_1, "cell 3 2,alignx center,growy");
		
		JButton infoButton = new JButton("פעולות נוספות/פרטים");
		infoButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		infoButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(selectedColumnIndex != -1 && selectedRowIndex != -1)
				{
					ArrayList<Object> message = new ArrayList<>();
					ArrayList<Object> respond = new ArrayList<>();
					message.add("getJarContents");
					DefaultTableModel model = (DefaultTableModel) table.getModel();
					
					String jarID = model.getValueAt(selectedRowIndex, 7).toString();
					message.add(jarID);
					try {
						polishClient = new RPCClient();
						respond=polishClient.call(message);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					if(respond.get(1).equals("valid"))
					{
						String endDate  = table.getModel().getValueAt(selectedRowIndex, 1).toString();
						myInfoFrame = new MyInfoFrame(myFrame,respond,selectedColumnIndex,selectedRowIndex,myPolishPanel,jarID,endDate);
					}
					else{
						
					}
				}
				else
					JOptionPane.showMessageDialog(myFrame,
        				    "יש לבחור ראשית צנצנת מהרשימה.","שגיאה",JOptionPane.ERROR_MESSAGE);
					//JOptionPane.showMessageDialog(myFrame, "נא לבחור שורה מהטבלה לפרטים");
				
				
			}
		});
		infoButton.setIcon(new ImageIcon(PolishPanel.class.getResource("/graphics/moreInformation.png")));
		add(infoButton, "cell 1 2,alignx left,growy");
		
		JButton button_3 = new JButton("החלפת כדוריות");
		button_3.setFont(new Font("Tahoma", Font.PLAIN, 13));
		button_3.setIcon(new ImageIcon(PolishPanel.class.getResource("/graphics/replacePellets48.png")));
		button_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(selectedColumnIndex != -1 && selectedRowIndex != -1)
				{
					DefaultTableModel model = (DefaultTableModel) table.getModel();
					String jarID = model.getValueAt(selectedRowIndex, 7).toString();
					ArrayList<Object>message = new ArrayList<>();
					ArrayList<Object>respond = new ArrayList<>();
					message.clear();
					respond.clear();
					message.add("replacePellets");
					message.add(jarID);
					Object[] options = { "כן", "לא" };
					int n = JOptionPane.showOptionDialog(myFrame, "האם אתה בטוח שברצונך לאפס את מחזור הכדוריות?", "איפוס מחזור כדוריות", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
					if (n==0)
	        		{
						try{
							polishClient = new RPCClient();
							respond = polishClient.call(message);
								//JOptionPane.showMessageDialog(myFrame, "מחזור הכדוריות אופס");
								JOptionPane.showMessageDialog(myFrame,
		            				    "מחזור הכדוריות אופס.","אישור",JOptionPane.INFORMATION_MESSAGE);
								selectedColumnIndex=-1;
								selectedRowIndex =-1;
								message.clear();
								message.add("initializePolishPane");
								respond = polishClient.call(message);
								
						}catch(Exception e1 )
						{
							e1.printStackTrace();
						}
	        		}
					else{
						
					}
					
				}
				else {
					JOptionPane.showMessageDialog(myFrame, "אנא בחר שורה מהטבלה לעיל טרם הלחיצה", "החלפת כדוריות", JOptionPane.WARNING_MESSAGE);
				}
			}
		});
		add(button_3, "cell 9 6,growx,aligny top");
		
		JPanel panel = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel.setBorder(new TitledBorder(null, "\u05DB\u05E2\u05EA \u05D1\u05DC\u05D9\u05D8\u05D5\u05E9", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel.setBackground(UIManager.getColor("InternalFrame.activeTitleBackground"));
		add(panel, "cell 1 5 9 1,grow");
		panel.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setEnabled(false);
		scrollPane_1.setViewportBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.add(scrollPane_1);
		
		table = new JTable();
		table.setFont(new Font("Tahoma", Font.PLAIN, 15));
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				/*
				selectedRowIndex = table.getSelectedRow();
				selectedColumnIndex = table.getSelectedColumn();
				selectedObject = (Object) table.getModel().getValueAt(selectedRowIndex, selectedColumnIndex);
				*/
				selectedRowIndex = table.convertRowIndexToModel(table.getSelectedRow());
				selectedColumnIndex = table.convertColumnIndexToModel(table.getSelectedColumn());
				selectedObject = (Object) table.getModel().getValueAt(selectedRowIndex, selectedColumnIndex);
				//System.out.println("Row is : ")
			}
		});
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u05D9\u05DE\u05D9\u05DD \u05DC\u05D9\u05E6\u05D9\u05D0\u05D4", "\u05D9\u05E6\u05D9\u05D0\u05D4 \u05E1\u05D5\u05E4\u05D9", "\u05E1\u05D4\"\u05DB", "\u05EA\u05D5\u05E1\u05E4\u05EA \u05D6\u05DE\u05DF", "\u05D9\u05E6\u05D9\u05D0\u05D4 \u05DE\u05E7\u05D5\u05E8\u05D9", "Topline", "\u05DE\u05D7\u05D6\u05D5\u05E8 \u05DB\u05D3\u05D5\u05E8\u05D9\u05D5\u05EA", "\u05E6\u05E0\u05E6\u05E0\u05EA"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table.getColumnModel().getColumn(0).setPreferredWidth(90);
		table.getColumnModel().getColumn(1).setPreferredWidth(90);
		table.getColumnModel().getColumn(2).setPreferredWidth(63);
		table.getColumnModel().getColumn(3).setPreferredWidth(82);
		table.getColumnModel().getColumn(4).setPreferredWidth(90);
		table.getColumnModel().getColumn(5).setPreferredWidth(111);
		table.getColumnModel().getColumn(6).setPreferredWidth(98);
		table.getColumnModel().getColumn(7).setPreferredWidth(54);
		scrollPane_1.setViewportView(table);
		
		JButton btnNewButton_1 = new JButton("סיים ליטוש\r\n");
		btnNewButton_1.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//check if any jar \ row from table is selected 
				if(selectedColumnIndex != -1 && selectedRowIndex != -1)
				{
					Object[] options = {"כן","לא"};
					int answer = JOptionPane.showOptionDialog(myFrame, "האם הינך בטוח שברצונך לסיים פוליש?", "סיים פעולת פוליש על צנצנת שנבחרה", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
					if(answer == 0)
					{
						DefaultTableModel model = (DefaultTableModel) table.getModel();
						
						String jarID = model.getValueAt(selectedRowIndex, 7).toString();
						//int jarIDInt = Integer.valueOf(jarID);
						//int a = table.convertRowIndexToView(jarIDInt);
						//jarID = model.getValueAt(selectedRowIndex, 7).toString();
						ArrayList<Object>message = new ArrayList<>();
						ArrayList<Object>respond = new ArrayList<>();
						ArrayList<Object>respond1 = new ArrayList<>();
						message.add("getJarContents");
						message.add(jarID);
						try{
							polishClient = new RPCClient();
							respond = polishClient.call(message);
							if(respond.get(1).equals("valid"))
							{
								int i=0,i1=0;
								do
								{
									String orderID =respond.get(2+i*2).toString();//Holds the OrderID's , not taking the quantity the is included in the query.
									String polishID;
									message.clear();
									message.add("setStatusIDByOrderID");
									message.add(orderID); 
									message.add("4");
									respond1=polishClient.call(message);
									respond1.clear();
									message.clear();
									message.add("getPolishID");
									message.add(jarID);
									message.add(orderID);
									respond1 = polishClient.call(message);
									polishID = respond1.get(2).toString();
									message.clear();
									message.add("setEndDateInPolishByPolishID");
									message.add(polishID);
									respond1 = polishClient.call(message);
									i++;
									i1=2+i*2;
									
								}while(i1<respond.size());
							}
						}
						catch(Exception e)
						{
							//e.printStackTrace();
						}
					
					
					
						//message.add("changeOrderStatus");
						//message.add(orderID);
						ArrayList<Object> message99 = new ArrayList<>();
						ArrayList<Object> respond99=null;
						message99.add("initializePolishPane");
						try{
							respond99 = polishClient.call(message99);
						}
						catch (Exception e1)
						{
							e1.printStackTrace();
						}
						myPolishPanel.setVariables(respond99);
						selectedColumnIndex=-1;
						selectedRowIndex=-1;
					}
				}
				else
					JOptionPane.showMessageDialog(myFrame,"בחר צנצנת מהטבלה לעיל");
			}
			
		});
		
		JButton button_5 = new JButton("יציאה");
		button_5.setFont(new Font("Tahoma", Font.PLAIN, 13));
		button_5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0)
			{
				Object[] options = {"כן","לא"};
        		int n = JOptionPane.showOptionDialog(myFrame, "האם ברצונך לצאת מהמערכת?","אישור יציאה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
        		
        		if (n==0)
        		{
        			if (polishClient != null)
                    {
                      try
                      {
                    	  polishClient.close();
                      }
                      catch (Exception ignore)
                      {}
                     }
            		
            		System.exit(0);
        		}
						
			}
		});
		button_5.setIcon(new ImageIcon(PolishPanel.class.getResource("/graphics/exit.png")));
		add(button_5, "cell 1 8,alignx left,growy");
		btnNewButton_1.setIcon(new ImageIcon(PolishPanel.class.getResource("/graphics/delete.png")));
		add(btnNewButton_1, "cell 3 8,alignx center,growy");
		
		JButton btnStartPolish = new JButton("התחל ליטוש");
		btnStartPolish.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btnStartPolish.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					myStartPolish = new StartPolishPanel(myFrame,myPolishPanel);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
				myFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);

				myFrame.setContentPane(myStartPolish);
				selectedColumnIndex=-1;
				selectedRowIndex=-1;
			}
		});
		btnStartPolish.setIcon(new ImageIcon(PolishPanel.class.getResource("/graphics/createReport.png")));
		add(btnStartPolish, "cell 9 8,grow");
		// TODO Auto-generated constructor stub
	}
/**
 * This method received the response from PolishFrame , where it had connected the DB and received the variables and sent it here to PolishPanel , now we set the related feields 
 * in this panel .	
 * @param response
 */
	void setVariables(ArrayList<Object> response)
    {
		DefaultTableModel model = (DefaultTableModel) table.getModel();
		System.out.println("In set variables");
		model.setRowCount(0);
		Long pelletsNew=(long) 0 ;
		String s = response.get(1).toString();
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); 
		// Getting the Date of today in Date format using Date + Calendar 
		Calendar today1 = Calendar.getInstance(); 
		Date day = new Date(today1.getTimeInMillis());
		//Row Sorter 
		 RowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(model);
		 table.setRowSorter(sorter);
		 //Row sorter end
		 
		if(s.equalsIgnoreCase("valid"))
		{
			//response.
			for(int j=0 ; j< response.size()-2;j++)
			{
				PolishFrameEntity myEntity = (PolishFrameEntity)response.get(j+2);
				String endingDate;
				Date entityBeginDate = myEntity.getBeginDate();
				Calendar cal1 = Calendar.getInstance();
				cal1.setTime(entityBeginDate);
				cal1.add(Calendar.DATE,(int)myEntity.getExtraDays());
				DateFormat formatDay = new SimpleDateFormat("yyyy/MM/dd");
				//endingDate = formatDay.format(cal1.getTime()).toString();
				endingDate=myEntity.getEndDate().toString();
				//Today's day
				Calendar calToday = Calendar.getInstance();
				Date todaysDate = new Date(calToday.getTimeInMillis());
				long howMuchLeft;
				howMuchLeft =myEntity.getEndDate().getTime() - todaysDate.getTime();
				howMuchLeft = howMuchLeft / (1000 * 60 * 60 * 24);
				String STRHowMuchLeft = String.valueOf(howMuchLeft);
				//long howMuchLedt = today.getTimeZone() - today.;
				model.addRow(new Object[]{STRHowMuchLeft,endingDate,myEntity.getTotalDays(),myEntity.getExtraDays(),myEntity.getOriginalEndDate(),myEntity.getTopline(),myEntity.getPelletescycles(),myEntity.getJarNum()});
			}
		//	youCanUpdatePelletsDB=true;
		}
    }
	
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
}
